<?php
require_once "facebook.php";

/**
 * Clase que permite realizar los metodos para test de las FB App
 *
 */  
class FacebookTest extends Facebook
{
    protected $app_access_token;

    /**
     *  1,2,3,4,5
     *
     */              
    protected $debug_level;
    public function setDebugLevel($level){
        $this->debug_level=$level;  
    }
    
    protected function debug($level,$msg){
        if($this->debug_level<=$level){
            $value = print_r($msg,true);
            error_log("\n$value", 3,APP_LOG);// dirname(__FILE__)."/facebook_test.log");
        }
    }
    
    /**
     * Obtenemos el access_token de la aplicacion para la conexion
     *
     */              
    public function getAppAccessToken(){
    	$params['grant_type']='client_credentials';
    	$params['client_id']=$this->getAppId();
    	$params['client_secret']=$this->getApiSecret();
        
        $this->debug(3,__METHOD__);
        $this->debug(3,$params);
            	
    	$url = $this->getUrl('graph','/oauth/access_token',$params);
        $this->debug(3,$url);
        
        $access_token = file_get_contents($url);
        $this->debug(3,$access_token);

        $this->app_access_token = explode('=',$access_token);
        $this->app_access_token = $this->app_access_token[1];
        
        return  $access_token;
    }
    
    /**
     * Retorno el listado de las cuentas de pruebas
     *
     */              
    public function getTestAccounts(){
        $params = array();
        $params['access_token']=$this->app_access_token;

        $this->debug(4,__METHOD__);
        $this->debug(4,$params);
        
    	$accounts = $this->apiTest("/accounts/test-users",'GET',$params);
        $this->debug(4,$accounts);
        
    	if( isset($accounts['data']) )
    		return $accounts;
    	else
    		return null;    
    }
    
    /**
     * Creamos una cuenta de prueba
     */         
    public function createTestAccount(){
    	$params = array();
    	$params['installed'] = 'true';
    	$params['permissions'] = 'offline_access,publish_stream,user_likes';
        $params['access_token'] = $this->app_access_token;
        
        $this->debug(3,__METHOD__);
        $this->debug(3,$params);
        
    	$account = $this->apiTest("/accounts/test-users", "POST", $params);
    	$this->persistTestAccount($account);
        return $account;    
    }
    

    public function getPersistedTestAccounts(){
        $file = FACEBOOK_TEST_USERS_DATA;//dirname(__FILE__)."/facebook_test.users.serialize";
        $accounts = array();
        if(file_exists($file)){
            $accounts_serialize = file_get_contents($file);
            $accounts = unserialize($accounts_serialize);
        }
        return $accounts;
    }
    /**
     * guardo la informacion de la cuenta creada
     */         
    public function persistTestAccount($account){
        $file = FACEBOOK_TEST_USERS_DATA;//dirname(__FILE__)."/facebook_test.users.serialize";
        $accounts = $this->getPersistedTestAccounts();
        // esta en el data
        $accounts[]=$account;
        file_put_contents($file, serialize($accounts));
    }
    
    /**
     * Eliminamos un usuario por id
     */         
    public function deleteTestAccount($fbId) {
        $params = array();
        $params['access_token'] = $this->app_access_token;
        
        $this->debug(3,__METHOD__);
        $args=func_get_args();$this->debug(3,$args);
        $this->debug(3,$params);
        
    	return $this->api("/$fbId", "DELETE",$params);
    }     
    
    /**
     * Eliminamos todas las cuentas 
     */         
    public function deleteAllTestAccounts() {
        $file = FACEBOOK_TEST_USERS_DATA;
        unlink($file);
        
        $accounts = $this->getTestAccounts();
        if(!$accounts) return false;
        
        foreach($accounts['data'] as $account){
            $this->deleteTestAccount($account['id']);
        }
    }
     
    /**
     * Buscamos a un usuarios de test por id
     *
     */              
    public function findTestAccount($fbID){
        $accounts = $this->getTestAccounts();
        if(!$accounts) return false;
        
        foreach($accounts['data'] as $account){
            if($account['id']==$fbID){
                return $account;
            }    
        }
        return false;
    }
    
    
    function addFriends($fbIdFrom,$fbIdTo,$accessTokenFrom){
       	$params = array();
        $params['access_token'] = $accessTokenFrom;
        
        $this->debug(3,__METHOD__);
        $args=func_get_args();$this->debug(3,$args);
        $this->debug(3,$params);
        
        return $this->api("/$fbIdFrom/friends/$fbIdTo", "post",$params);
    }
    function confirmFriends($fbIdFrom,$fbIdTo,$accessTokenTo){
       	$params = array();
        $params['access_token'] = $accessTokenTo;
        
        $this->debug(3,__METHOD__);
        $args=func_get_args();$this->debug(3,$args);
        $this->debug(3,$params);

        return $this->api("/$fbIdTo/friends/$fbIdFrom", "post",$params);
    }    
    
    
    
    
    
    
    /**
     * Personalizamos la llamada al API, ya que es necesario indicar el AppId en
     * todas las llamadas     
     *
     */              
    public function apiTest(){
        $args = func_get_args();
        if (is_array($args[0])) {
          return $this->_restserver($args[0]);
        } else {
            $args[0] = '/'.$this->getAppId().$args[0];
            
            $this->debug(3,__METHOD__);
            $this->debug(3,$args);
            
            return call_user_func_array(array($this, '_graph'), $args);
        }
    }      
}
